package com.itcam.interview.pro04thread;

import lombok.Getter;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class ThreadLocalDemo {
    public static void main(String[] args) throws InterruptedException {
        SU7 su7 = new SU7();
        CountDownLatch countDownLatch = new CountDownLatch(3);

        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(3) + 1; j++) {
                        su7.saleTotal();
                        su7.salePersonal();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t" + "号销售卖出：" + su7.salePersonal.get() + "辆su7");
                } finally {
                    countDownLatch.countDown();
//                    su7.salePersonal.remove(); // 暂不加
                }
            }, String.valueOf(i)).start();
        }
        countDownLatch.await();

        System.out.println(Thread.currentThread().getName() + "共售出:" + su7.getSaleTotal() + "辆su7");
    }
}

class SU7 {

    @Getter
    private int saleTotal;

    public synchronized void saleTotal() {
        saleTotal++;
    }

    //    ThreadLocal<Integer> salePersonal = new ThreadLocal<>() {
//        @Override
//        protected Integer initialValue() {
//            return 0;
//        }
//    };
    ThreadLocal<Integer> salePersonal = ThreadLocal.withInitial(() -> 0);

    public void salePersonal() {
        salePersonal.set(1 + salePersonal.get());
    }
}